package com.pactera.asmp.server.common.websocket.webrtc;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ projectName: webRtc_Server
 * @ package:     com.gientech.webrtc_server.control
 * @ className:   WebRTCSessionManager
 * @ author:      Carson
 * @ description:
 * @ date:        2023/5/17/017 11:24
 * @ version:     1.0
 */
@Slf4j
public class WebRTCSessionManager {

    private static final Map<String, Object> sessionMap = new ConcurrentHashMap<>();

    public synchronized static void setSession(String userId,String type, Session session) {
        sessionMap.put(userId, new SessionInfo(type,session));
    }

    public static String removeSession(String sessionId) {

        if (null == sessionId) {
            return null;
        }
        String cuid=null;
        for (Map.Entry<String, Object> entry : sessionMap.entrySet()) {
            String k = entry.getKey();
            Object v = entry.getValue();
            if (sessionId.equals(((SessionInfo) v).getSession().getId())) {

                sessionMap.remove(k);
                log.info("移除session用户 id：{},mode：{}", k, ((SessionInfo) v).getType());
                if(((SessionInfo) v).getType().equals("jpeg") || ((SessionInfo) v).getType().equals("camera")){
                    cuid=k;
                    break;
                }
            }
        }
        return cuid;
    }

    public static void sendMessage(String userId, String message, Session respsession) throws IOException {

        SessionInfo sessionInfo=((SessionInfo)sessionMap.get(userId));
        if(sessionInfo==null)
        {
            Model model = new Model("response", "WebRTCServer", "", "暂无摄像头", "false");
            respsession.getBasicRemote().sendText(JSON.toJSONString(model));
            model.setIsSuccess("false");
            log.info("目标未注册");
            return;
        }

        Session session = sessionInfo.getSession();
        if (session != null) {
            synchronized (session) {
                try {
                    session.getBasicRemote().sendText(message);
//                    log.info("完成给用户{}发送消息：{}", userId, message);
                } catch (IOException e) {
                    log.info("发送websocket消息异常", e);
                }
            }
        } else {
            Model model = new Model("response", "WebRTCServer", "", "目标连接异常", "false");
            respsession.getBasicRemote().sendText(JSON.toJSONString(model));
            model.setIsSuccess("false");
            log.info("目标连接异常");
        }
    }
}



